var http = require('http');
var fs = require('fs');
var path = require('path');
const del = require('./remove');

var html = path.join(__dirname,'index.html');
var filesPath = path.join(__dirname,"/files");

var data = [];

var roterTable = {
    "GET":{
        '/': (req,res) => {
            var readStream = fs.createReadStream(html);
            res.writeHead(200,{'content-type':'text/html;charset=utf-8'})
            readStream.pipe(res);
            
        },
        '/1.png' : (req,res) => {
            var imgPath = path.join(__dirname,'/1.png');
            var imgObj = fs.readFileSync(imgPath);
            res.writeHead(200,{'content-type':'image/png'});
            res.write(imgObj);
            res.end()
        },
        '/getlist':  (req,res) => {
            data = [];
            fs.readdir(filesPath,(e,list) => {
                // console.log(list);
                for (let i = 0; i < list.length; i++) {
                    let tempObj = {fileType:"",fileName:list[i],fileSize:0,fileTime:"",fileTimeId:""}
                    var childPath = path.join(filesPath,`/${list[i]}`);
                    var stat = fs.statSync(childPath);
                    var timeObj = new Date(stat.birthtimeMs);
                    var time = timeObj.getFullYear()+"-" + (timeObj.getMonth()+1)+"-"+timeObj.getDate();
                    // console.log(stat);
                    // console.log(time);
                    tempObj.fileSize = stat.size+'byte';
                    tempObj.fileTime = time;
                    tempObj.fileTimeId = stat.birthtimeMs;
                    if (stat.isDirectory()) {
                        tempObj.fileType = 'folder';
                    }
                    if (stat.isFile()) {
                        tempObj.fileType = 'file';
                    }
                    
                    data.push(tempObj)
                }
                var resData = JSON.stringify(data);
                res.setHeader('content-type','text/plain;charset=utf-8')
                res.end(resData);
            });
            
            
        },
        '/getfile' : (req,res) => {
            let fileIdarr = req.url.split("?");
            let fileIdStrraw = fileIdarr[1];
            let fileIdStrMidraw = fileIdStrraw.split("=");
            let fileIdstr = fileIdStrMidraw[1].slice(4);//获取要获取的元素的id
            let getFileName;
            for (let i = 0; i < data.length; i++) {
                if (fileIdstr == data[i].fileTimeId) {
                    getFileName = data[i].fileName;
                } 
            }
            let getFilePath = path.join(__dirname,`/files/${getFileName}`);
            fs.stat(getFilePath,(e,s) => {
                console.log("执行了！")
                if (s.isDirectory()) {
                    // console.log("isDir!");
                }
                else if (s.isFile()) {
                    fs.readFile(getFilePath,(e,data)=>{
                        res.end(data);
                    })
                }
            })
            
        },
        "/del": (req,res) => {//删除发回来的get请求格式：/del?del1Id=del2019-9-3
            var fileIdArr = req.url.split("?");
            var fileIdStrRaw = fileIdArr[1];
            var fileIdStrMidRaw = fileIdStrRaw.split("=");
            var fileIdStr = fileIdStrMidRaw[1].slice(3);//获取要删除的元素的id
            var delFileName;
            // console.log(fileIdStr);
            // console.log(data);
            for (let i = 0; i < data.length; i++) {
                if (fileIdStr == data[i].fileTimeId) {
                    delFileName = data[i].fileName;
                } 
            }
            var delFilePath = path.join(__dirname,`/files/${delFileName}`);
            // console.log(delFilePath);
            del(delFilePath);
            // 删除后重新读取
            let list = fs.readdirSync(filesPath);
            for (let i = 0; i < list.length; i++) {
                let tempObj = {fileType:"",fileName:list[i],fileSize:0,fileTime:"",fileTimeId:""}
                let childPath = path.join(filesPath,`/${list[i]}`);
                let stat = fs.statSync(childPath);
                let timeObj = new Date(stat.birthtimeMs);
                let time = timeObj.getFullYear()+"-" + (timeObj.getMonth()+1)+"-"+timeObj.getDate();
                // console.log(stat);
                // console.log(time);
                tempObj.fileSize = stat.size+'byte';
                tempObj.fileTime = time;
                tempObj.fileTimeId = stat.birthtimeMs;
                if (stat.isDirectory()) {
                    tempObj.fileType = 'folder';
                }
                if (stat.isFile()) {
                    tempObj.fileType = 'file';
                }
                
                data.push(tempObj)
            }
            let resData = JSON.stringify(data);
            res.setHeader('content-type','text/plain;charset=utf-8')
            res.end(resData);
        }
    },
    
    
}


http.createServer((req,res) => {
    var url = req.url.split("?");//加入?分割url来实现识别del请求
    // console.log(url)
    // console.log(req.method)
    // console.log(req)
    if (roterTable[req.method][url[0]] == undefined) {
        res.statusCode = 404;
        res.end("Page not found");
    }
    if (roterTable[req.method][url[0]] != undefined) {//解决请求图片时报错
        roterTable[req.method][url[0]](req,res)
    }
    console.log(url);
    
    
}).listen(8081);
console.log("server is listening 8081");